import axios from 'axios';
import { BaseResult } from './BaseResult';
import debounce from 'lodash/debounce';
import { Loading } from 'element-ui';

axios.defaults.timeout = 50000;//设置超时时间
let loadingInstance; //loading 实例
let needLoadingRequestCount = 0; //当前正在请求的数量


axios.interceptors.request.use(config => {
    showLoading();
    return config;
}, error => {
    closeLoading();
    return Promise.reject(error);
});
axios.interceptors.response.use(response => {
    closeLoading();
    return response;
}, error => {
    closeLoading();
    //异常处理
    return Promise.reject(error);
});
let curRequestTime = 1;
let myInterval;

/**
 * 显示loading
 */
function showLoading() {
    if (needLoadingRequestCount === 0 && !loadingInstance) {
        curRequestTime = 1;
        loadingInstance = Loading.service({
            fullscreen: true,
            lock: true,
            text: curRequestTime + 'S 正在请求中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.6)'
        }
        );
        let loadingClass = document.getElementsByClassName('el-loading-text')[0];
        myInterval = setInterval(() => {
            curRequestTime++;
            loadingClass.innerHTML = curRequestTime + 'S 正在请求中...';
        }, 1000)
    }
    needLoadingRequestCount++;
}

/**
 * 关闭loading
 */
function closeLoading() {
    setTimeout(() => {
        needLoadingRequestCount--;
        needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 保证大于等于0
        if (needLoadingRequestCount === 0) {
            if (loadingInstance) {
                hideLoading();
            }
        }
    });
}

/**
 * 关闭loading的直接步骤
 */
let hideLoading = debounce(() => {
    loadingInstance.close();
    loadingInstance = null;
    clearInterval(myInterval)
}, 300);//300

function getAxiosConfig(mode, url,params) {
    switch (mode) {
        case 'post':
            return {
                method: 'post',
                url,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Access-Control-Allow-Origin': '*',
                    'USER-KEY': localStorage.getItem('user_key')
                },
                data: params,
                responseType: '',
            };
        case 'get':
            return {
                method: 'get',
                url,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Access-Control-Allow-Origin': '*',
                    'USER-KEY': localStorage.getItem('user_key')
                },
                params: params,
                responseType: '',
            };
        case 'FormData':
            let formParams = new FormData()
            for (let key in params) {
                formParams.append(key, params[key])
            }
            return {
                method: 'post',
                url,
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Access-Control-Allow-Origin': '*',
                    'USER-KEY': localStorage.getItem('user_key')
                },
                data: formParams,
                responseType: '',
            };
    }
}
/**
 * 封装直接使用的post请求方法
 * @param {Object} url
 * @param {Object} params
 */
export function axiosPost(mode, url, params) {
    //获取配置请求的配置文件
    const config = getAxiosConfig(mode,url, params)
    return new Promise((resolve, reject) => {
        axios(config)
            .then((response) => {
                resolve(response.data);
            })
            .catch((err) => {
                if (err) {
                    try {
                        switch (err.response.status) {
                            case 400:
                                err.message = '请求错误';
                                break;
                            case 401:
                                err.message = '未授权，请登录';
                                break;
                            case 403:
                                err.message = '拒绝访问';
                                break;
                            case 404:
                                err.message = '请求地址出错';
                                break;
                            case 408:
                                err.message = '请求超时';
                                break;
                            case 500:
                                if (err.response.data.msg) {
                                    err.message = err.response.data.msg;
                                } else {
                                    err.message = '服务器内部错误';
                                }
                                break;
                            case 501:
                                err.message = '服务未实现';
                                break;
                            case 502:
                                err.message = '网关错误';
                                break;
                            case 503:
                                err.message = '服务不可用';
                                break;
                            case 504:
                                err.message = '网关超时';
                                break;
                            case 505:
                                err.message = 'HTTP版本不受支持';
                                break;
                            default:
                        }
                        reject(new BaseResult(err.response.status, err.message, url));
                    } catch (e) {
                        reject(new BaseResult(-888, '请求超时', url));
                    }
                }
            });
    });
}
